/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package trab_sd;

import java.net.*;
import java.io.*;
import java.util.*;

/**
 *
 * @author moacirnq
 */
public class FileListRemove implements Runnable{
	private Socket connection;
	private ObjectOutputStream out;
	private Scanner in;
	private UserID dst, owner;
	private String fname;
	private User localUser;
	private int i =0;
	
	public FileListRemove (UserID dst, UserID fileOwner, String fname, User localUser ) {
		this.owner = fileOwner;
		this.fname = fname;
		this.dst = dst;
		this.localUser = localUser;
		
		//Tenta estabelecer a conexao e abrir os streams
		try {
			connection = new Socket( dst.getName(), dst.getPort() );
			
			//Estabelece o tempo maximo de inatividade como 50s
			connection.setSoTimeout( 50000 );
		}
		catch ( SocketTimeoutException | ConnectException | UnknownHostException  ste) {
			if ( dst.equals(localUser.getServerID()) ) {
				localUser.removeOfflineUser(dst);
			}
			else {
				OfflineUserMsg of = new OfflineUserMsg( dst, localUser.getServerID());
				of.run();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void run(){
		String ans = "NOTOK";
		try {
			out = new ObjectOutputStream( connection.getOutputStream() );
			out.writeUTF("REMOVE_FILE");
			out.flush();
			out.writeUTF(fname);
			out.flush();
			out.writeObject(owner);
			out.flush();
			in = new Scanner( connection.getInputStream() );
			ans = in.next();
			
		}
		catch (Exception e) {
			if (true) {
				i++;
				run();
			}
			else {
				e.printStackTrace();
			}
		}
		finally {
			try {
				connection.close();
				out.close();
				in.close();
			} catch (Exception ex) {
				//ex.printStackTrace();
			}
			return;
		}
	}
}
